package com.briup.homework.chap10.bean;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

public class Account {
    private String name;
    private Double balance;

    public Account() {
    }

    public Account(String name, Double balance) {
        this.name = name;
        this.balance = balance;
    }

    // 给一些逻辑方法
    // 存钱
    public Double deposit(Double amount) {
        if(amount<=0){
            throw new RuntimeException("存钱数目不符合实际");
        }
        BigDecimal b1 = BigDecimal.valueOf(balance);
        BigDecimal b2 = BigDecimal.valueOf(amount);
        BigDecimal add = b1.add(b2);
        balance = add.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return balance;
    }
    // 取钱
    public Double withdraw(Double amount) {
        if(amount<=0){
            throw new RuntimeException("取钱数目不符合实际");
        }
        if(amount>balance){
            throw new RuntimeException("银行卡余额不足");
        }
        BigDecimal b1 = BigDecimal.valueOf(balance);
        BigDecimal b2 = BigDecimal.valueOf(amount);
        BigDecimal subtract = b1.subtract(b2);
        balance = subtract.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return balance;
    }
    // 转账
    public void transfer(Account to, double amount){
        // from 就是this
        // 因为需要两把锁，所以要固定一下锁的顺序
//        Account firstAccount = (name.compareTo(to.getName()) < 0) ? this : to;
//        Account secondAccount =(name.compareTo(to.getName()) < 0) ? to : this;

        Account firstAccount = this;
        Account secondAccount = to;

        synchronized (firstAccount){
            synchronized (secondAccount){
                // 转账
                firstAccount.withdraw(amount);
                secondAccount.deposit(amount);
                // 做一个输出，解释一下转账的过程
                // 这个线程 转涨是从哪到哪，转账完成之后，各自的余额是多少
                System.out.println(Thread.currentThread().getName()
                        + "transferred " + amount + " from " + name + " to " + to.getName()
                        + ". " + name + " Balance: " + balance + ", "
                        + to.getName() + "Balance: " + to.getBalance());
            }
        }
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "name='" + name + '\'' +
                ", balance=" + balance +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Account account)) return false;
        return Objects.equals(name, account.name) && Objects.equals(balance, account.balance);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, balance);
    }
}
